package com.example.srb.core.controller.api;


import com.alibaba.fastjson.JSON;
import com.example.srb.common.result.Result;
import com.example.srb.core.hfb.RequestHelper;
import com.example.srb.core.pojo.entity.LendReturn;
import com.example.srb.core.service.LendReturnService;
import com.example.srb.service2base.util.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 还款记录表 前端控制器
 * </p>
 *
 * @author Helen
 * @since 2021-02-20
 */
@RestController
@RequestMapping("/api/core/lendReturn")
@Slf4j
@Api(tags = "还款计划")
public class LendReturnController {

    @Resource
    private LendReturnService lendReturnService;

    @ApiOperation("获取列表")
    @GetMapping("/list/{lendId}")
    public Result list(@ApiParam(value = "标的id",required = true) @PathVariable Long lendId){

        List<LendReturn> lendReturnList = lendReturnService.selectByLendId(lendId);
        return Result.ok().data("list",lendReturnList);
    }

    @ApiOperation("用户还款")
    @PostMapping("/auth/commitReturn/{lendReturnId}")
    public Result commitReturn(@ApiParam(value = "还款id",required = true) @PathVariable Long lendReturnId,
                               HttpServletRequest request){
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);
        String formStr = lendReturnService.commitReturn(lendReturnId,userId);
        return Result.ok().data("formStr",formStr);
    }

    @ApiOperation("还款异步回调")
    @PostMapping("/notifyUrl")
    public String notifyUrl(HttpServletRequest request){
        Map<String, Object> paramMap = RequestHelper.switchMap(request.getParameterMap());
        log.info(  "还款异步回调接收的参数--> " + JSON.toJSONString(paramMap));

        if (RequestHelper.isSignEquals(paramMap)){
            if ("0001".equals(paramMap.get("resultCode"))){
                lendReturnService.notifyUrl(paramMap);
            }else {
                log.info("还款异步回调失败" + JSON.toJSONString(paramMap));
                return "fail";
            }
        }else {
            log.info("还款异步回调验签错误" + JSON.toJSONString(paramMap));
            return "fail";
        }

        return "success";
    }
}

